package core

const (
	DIR  = "dir"
	FILE = "file"
)

type Node struct {
	Name     string
	Type     string
	SubNodes map[string]Node
	Blocks   []string
}

func (n *Node) IsFile() bool {
	return n.Type == FILE
}

func (n *Node) AddBlock(workerID string) {
	n.Blocks = append(n.Blocks, workerID)
}

func (n *Node) IsDir() bool {
	return n.Type == DIR
}

func (n *Node) Ls() []string {
	keys := make([]string, 0, len(n.SubNodes))
	for k := range n.SubNodes {
		keys = append(keys, k)
	}
	return keys
}

func (n *Node) Contains(name string) bool {
	_, ok := n.SubNodes[name]
	return ok
}

func (n *Node) Cd(name string) *Node {
	node, ok := n.SubNodes[name]
	if !ok {
		return nil
	}
	return &node
}

func (n *Node) Update(name string, node *Node) {
	n.SubNodes[name] = *node
}

func (n *Node) Mkdir(name string) bool {
	if n.Contains(name) {
		return false
	}
	n.SubNodes[name] = Node{
		Name:     name,
		Type:     DIR,
		SubNodes: make(map[string]Node),
	}
	return true
}

func (n *Node) Touch(name string) bool {
	if n.Contains(name) {
		return false
	}
	n.SubNodes[name] = Node{
		Name: name,
		Type: FILE,
	}
	return true
}

func (n *Node) Rm(name string) bool {
	if !n.Contains(name) {
		return false
	}
	delete(n.SubNodes, name)
	return true
}
